#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "aiclient.h"
#include "historymanager.h"
#include "settingdialog.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QScrollArea>
#include <QWidget>
#include <QLabel>
#include <QMessageBox>
#include <QDateTime>
#include <QClipboard>
#include <QFileDialog>
#include <QTextStream>
#include <QScrollBar>
#include <QTimer>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , m_aiClient(new AIClient(this))
    , m_historyManager(new HistoryManager(this))
    , m_currentConversationId("")
{
    ui->setupUi(this);
    setupUI();
    loadHistoryList();

    // 连接信号槽
    connect(m_sendBtn, &QPushButton::clicked, this, &MainWindow::onSendClicked);
    connect(m_inputEdit, &QLineEdit::returnPressed, this, &MainWindow::onSendClicked);
    connect(m_aiClient, &AIClient::answerReady, this, &MainWindow::onAnswerReceived);
    connect(m_aiClient, &AIClient::errorOccurred, this, &MainWindow::onNetworkError);
    connect(m_historyList, &QListWidget::itemClicked, this, &MainWindow::onHistoryItemClicked);
    connect(m_clearHistoryBtn, &QPushButton::clicked, this, &MainWindow::onClearHistoryClicked);
    connect(m_settingsBtn, &QPushButton::clicked, this, &MainWindow::onSettingsClicked);
    connect(m_copyBtn, &QPushButton::clicked, this, &MainWindow::onCopyAnswerClicked);
    connect(m_exportBtn, &QPushButton::clicked, this, &MainWindow::onExportHistoryClicked);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::setupUI()
{
    setWindowTitle("智能问答系统");
    setMinimumSize(1000, 700);

    // 主布局
    QWidget *centralWidget = new QWidget(this);
    QHBoxLayout *mainLayout = new QHBoxLayout(centralWidget);

    // 左侧历史记录面板
    QWidget *historyWidget = new QWidget();
    QVBoxLayout *historyLayout = new QVBoxLayout(historyWidget);
    historyLayout->addWidget(new QLabel("历史对话"));

    m_historyList = new QListWidget();
    historyLayout->addWidget(m_historyList);

    QHBoxLayout *historyBtnLayout = new QHBoxLayout();
    m_clearHistoryBtn = new QPushButton("清空历史");
    m_exportBtn = new QPushButton("导出记录");
    historyBtnLayout->addWidget(m_clearHistoryBtn);
    historyBtnLayout->addWidget(m_exportBtn);
    historyLayout->addLayout(historyBtnLayout);

    historyWidget->setMinimumWidth(200);
    historyWidget->setMaximumWidth(250);
    mainLayout->addWidget(historyWidget);

    // 中间聊天区域
    QWidget *chatWidget = new QWidget();
    QVBoxLayout *chatLayout = new QVBoxLayout(chatWidget);

    m_chatDisplay = new QTextEdit();
    m_chatDisplay->setReadOnly(true);
    m_chatDisplay->setStyleSheet("background-color: #F5F5F5; border: none;");
    chatLayout->addWidget(m_chatDisplay);

    QHBoxLayout *inputLayout = new QHBoxLayout();
    m_inputEdit = new QLineEdit();
    m_inputEdit->setPlaceholderText("请输入问题，按Enter发送...");
    m_inputEdit->setStyleSheet("border: 1px solid #CCCCCC; border-radius: 4px; padding: 5px;");

    m_sendBtn = new QPushButton("发送");
    m_sendBtn->setStyleSheet("background-color: #07C160; color: white; border-radius: 4px; padding: 5px 15px;");

    inputLayout->addWidget(m_inputEdit);
    inputLayout->addWidget(m_sendBtn);
    chatLayout->addLayout(inputLayout);

    mainLayout->addWidget(chatWidget, 1);

    // 右侧功能面板
    QWidget *funcWidget = new QWidget();
    QVBoxLayout *funcLayout = new QVBoxLayout(funcWidget);
    funcWidget->setMinimumWidth(150);
    funcWidget->setMaximumWidth(200);

    m_settingsBtn = new QPushButton("设置");
    m_copyBtn = new QPushButton("复制答案");

    funcLayout->addWidget(m_settingsBtn);
    funcLayout->addWidget(m_copyBtn);
    funcLayout->addStretch();

    mainLayout->addWidget(funcWidget);

    setCentralWidget(centralWidget);
}

void MainWindow::onAnswerReceived(const QString &answer)
{
    // 移除"正在思考"占位符（找到最后一段并替换）
    QString html = m_chatDisplay->toHtml();
    html = html.replace(QRegExp("<div style='text-align: left; margin: 10px 0;'>.*正在思考中...*</div>"), "");
    m_chatDisplay->setHtml(html);

    // 显示AI回答
    appendMessage(answer, false);

    // 保存到历史记录
    m_historyManager->addMessage(m_currentConversationId, getCurrentTimeString(),
                                m_inputEdit->text(), answer);
    loadHistoryList();

    // 确保滚动条始终在底部，显示最新消息
    m_chatDisplay->verticalScrollBar()->setValue(m_chatDisplay->verticalScrollBar()->maximum());
}

void MainWindow::onSendClicked()
{
    QString question = m_inputEdit->text().trimmed();
    if (question.isEmpty()) return;

    // 显示用户问题
    appendMessage(question, true);

    // 清空输入框
    m_inputEdit->clear();

    // 发送问题到AI
    if (m_currentConversationId.isEmpty()) {
        // 新对话
        m_currentConversationId = QString("conv_%1").arg(QDateTime::currentMSecsSinceEpoch());
    }
    m_aiClient->sendQuestion(question, m_currentConversationId);

    // 临时显示"正在思考"
    QTextCursor cursor = m_chatDisplay->textCursor();
    cursor.movePosition(QTextCursor::End);
    m_chatDisplay->setTextCursor(cursor);
    m_chatDisplay->insertHtml("<div style='text-align: left; margin: 10px 0;'>"
                             "<span style='background-color: #E0E0E0; padding: 8px 12px; border-radius: 8px; display: inline-block;'>"
                             "正在思考中...</span></div>");
    m_chatDisplay->insertHtml("<div style='text-align: left; margin: 10px 0;'>"
                             "<span style='background-color: #E0E0E0; padding: 8px 12px; border-radius: 8px; display: inline-block;'>"
                             "正在思考中...</span></div>");
    
    // 确保滚动条在底部
    m_chatDisplay->verticalScrollBar()->setValue(m_chatDisplay->verticalScrollBar()->maximum());
}

void MainWindow::appendMessage(const QString &text, bool isUser)
{
    QString timeStr = getCurrentTimeString();
    QString html;

    if (isUser) {
        // 用户消息：靠右，绿色背景
        html = QString("<div style='text-align: right; margin: 10px 0;'>"
                      "<div style='display: inline-block; text-align: left; max-width: 70%;'>"
                      "<span style='background-color: #95EC69; padding: 8px 12px; border-radius: 8px; display: inline-block;'>%2</span><br>"
                      "<span style='font-size: 8pt; color: #888888; margin-top: 4px; display: inline-block;'>%1</span>"
                      "</div></div>").arg(timeStr).arg(text.toHtmlEscaped());
    } else {
        // AI消息：靠左，白色背景
        html = QString("<div style='text-align: left; margin: 10px 0;'>"
                      "<div style='display: inline-block; text-align: left; max-width: 70%;'>"
                      "<span style='background-color: white; padding: 8px 12px; border-radius: 8px; display: inline-block; border: 1px solid #EEEEEE;'>%2</span><br>"
                      "<span style='font-size: 8pt; color: #888888; margin-top: 4px; display: inline-block;'>%1</span>"
                      "</div></div>").arg(timeStr).arg(text.toHtmlEscaped());
    }

    // 关键修改：先移动光标到文档末尾，再插入内容
    QTextCursor cursor = m_chatDisplay->textCursor();
    cursor.movePosition(QTextCursor::End);
    m_chatDisplay->setTextCursor(cursor);
    m_chatDisplay->insertHtml(html);

    // 确保滚动条始终在底部，显示最新消息
    m_chatDisplay->verticalScrollBar()->setValue(m_chatDisplay->verticalScrollBar()->maximum());
}
void MainWindow::onNetworkError(const QString &error)
{
    QMessageBox::warning(this, "网络错误", error);
    // 移除"正在思考"占位符
    QString html = m_chatDisplay->toHtml();
    html = html.replace(QRegExp("<div style='text-align: left; margin: 10px 0;'>.*正在思考中...*</div>"), "");
    m_chatDisplay->setHtml(html);
}

void MainWindow::loadHistoryList()
{
    m_historyList->clear();
    QMap<QString, QString> conversations = m_historyManager->getConversationList();
    for (auto it = conversations.begin(); it != conversations.end(); ++it) {
        new QListWidgetItem(it.value(), m_historyList);
        m_historyList->item(m_historyList->count() - 1)->setData(Qt::UserRole, it.key());
    }
}

void MainWindow::onHistoryItemClicked(QListWidgetItem *item)
{
    QString convId = item->data(Qt::UserRole).toString();
    showConversation(convId);
    m_currentConversationId = convId;
}

void MainWindow::showConversation(const QString &convId)
{
    m_chatDisplay->clear();
    QList<QPair<QString, QString>> messages = m_historyManager->getMessages(convId);

    for (const auto &msg : messages) {
        appendMessage(msg.first, true);  // 用户消息
        appendMessage(msg.second, false); // AI回复
    }
    
    // 确保滚动条在底部
    m_chatDisplay->verticalScrollBar()->setValue(m_chatDisplay->verticalScrollBar()->maximum());
}

void MainWindow::onClearHistoryClicked()
{
    if (QMessageBox::question(this, "确认清空", "确定要清空所有历史记录吗？") == QMessageBox::Yes) {
        m_historyManager->clearAllHistory();
        m_chatDisplay->clear();
        m_currentConversationId = "";
        loadHistoryList();
    }
}

void MainWindow::onSettingsClicked()
{
    SettingDialog dialog(this);
    dialog.exec();
}

void MainWindow::onCopyAnswerClicked()
{
    // 获取最后一个AI回答
    QString html = m_chatDisplay->toHtml();
    QRegExp rx("<div style='text-align: left; margin: 10px 0;'>.*?<span.*?>(.*?)</span>.*?</div>");
    rx.setMinimal(true);

    if (rx.indexIn(html) != -1) {
        QString answer = rx.cap(1);
        QApplication::clipboard()->setText(answer);
        QMessageBox::information(this, "复制成功", "答案已复制到剪贴板");
    } else {
        QMessageBox::warning(this, "复制失败", "没有可复制的答案");
    }
}

void MainWindow::onExportHistoryClicked()
{
    if (m_currentConversationId.isEmpty()) {
        QMessageBox::warning(this, "导出失败", "没有选中的对话");
        return;
    }

    QString fileName = QFileDialog::getSaveFileName(this, "导出对话", "", "文本文件 (*.txt)");
    if (fileName.isEmpty()) return;

    QFile file(fileName);
    if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QTextStream out(&file);
        QList<QPair<QString, QString>> messages = m_historyManager->getMessages(m_currentConversationId);

        out << "对话记录 - " << QDateTime::currentDateTime().toString() << "\n\n";
        for (int i = 0; i < messages.size(); ++i) {
            out << "你: " << messages[i].first << "\n";
            out << "AI: " << messages[i].second << "\n\n";
        }
        file.close();
        QMessageBox::information(this, "导出成功", "对话记录已导出到 " + fileName);
    }
}

QString MainWindow::getCurrentTimeString()
{
    return QDateTime::currentDateTime().toString("HH:mm:ss");
}
